/**
 * 微信登录按钮控件
 */
var WeChatLoginBtnUnit = LoginBtnUnit.extend({
    _reciveCodeKey: EventKey.ReceiveWechatCode,
    _authReq: 'WeichatCode',
    _ccsFileName: res.WeChatBtnUnit_json,

    initUnit: function () {
        LoginBtnUnit.prototype.initUnit.call(this);
        this._addEventListener(EventKey.QuickLogin, this._quickLogin.bind(this));
    },

    _quickLogin: function () {
        var wxOpenid = cc.sys.localStorage.getItem('wx_openid');
        if (!isNullString(wxOpenid)) {
            this._click();
        }
    },
    /**
     * 是否安装
     * @returns {boolean}
     * @protected
     */
    _isInstalled: function () {
        return WeChatUtil.isInstalled();
    },
    /**
     * 未安装提示
     */
    showNoInstalledAlert: function () {
        showAlert('您没安装微信!');
    },
    redirectLogin: function () {
        LoginBtnUnit.prototype.redirectLogin.call(this);
        showLoading('拉取微信授权中..');
        var openid = cc.sys.localStorage.getItem('wx_openid');
        if (isNullString(openid)) {
            WeChatUtil.redirectLogin();
        } else {
            var response = {
                openid: cc.sys.localStorage.getItem('wx_openid'),
                nickname: decodeURIComponent(cc.sys.localStorage.getItem('nickname')),
                sex: cc.sys.localStorage.getItem('sex'),
                province: cc.sys.localStorage.getItem('province'),
                city: cc.sys.localStorage.getItem('city'),
                country: cc.sys.localStorage.getItem('country'),
                headimgurl: cc.sys.localStorage.getItem('headimgurl'),
                unionid: cc.sys.localStorage.getItem('unionid')
            };
            this.doLogin(response, 'wx');
        }
    },
    _receiveCode: function (data) {
        LoginBtnUnit.prototype._receiveCode.call(this);
        if (data == "null") {//用户没有授权微信登录
            hideLoading();
            return;
        }
        if (isNullString(data.code)) {
            showAlert('微信授权code错误，请重新登录');
            return;
        }
        if (data.key && data.data) {
            this._requestAuth(data.code, data.key, data.data);
        } else {
            this._requestWxAuth(data.code);
        }
    },
    /**
     * 直接请求微信
     * @private
     */
    _requestWxAuth: function (code) {
        var appid = app.wxAppid;
        //var appsecret = getDAes(app.wxSecret);
        var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        url += 'appid=' + appid;
        url += '&secret=' + app.wxSecret;
        url += '&code=' + code;
        url += '&grant_type=authorization_code';

        http.get(url, this._requestWxAuthSuccess.bind(this), this._requestWxAuthFailure.bind(this));
    },
    /**
     * 直接请求微信成功
     * @param response
     * @private
     */
    _requestWxAuthSuccess: function (response) {
        var respJson = JSON.parse(response);
        if (respJson['errcode']) {
            showAlert('微信登录错误返回码：' + respJson['errcode']);
            // showAlert('您的微信授权信息已失效, 请重新登录');
        } else {
            var accessToken = respJson['access_token'];
            var openid = respJson['openid'];
            this._requestWxLogin(accessToken, openid);
        }
    },
    /**
     * 请求微信登录
     * @private
     */
    _requestWxLogin: function (accessToken, openid) {
        var url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' + accessToken + '&openid=' + openid;
        http.get(url, this._requestAuthSuccess.bind(this), this._requestAuthFailure.bind(this));
    },
    _requestWxAuthFailure: function () {
        showAlert('微信授权请求失败!请重新登录');
    },
    _requestAuthFailure: function () {
        LoginBtnUnit.prototype._requestAuthFailure.call(this);
        cc.sys.localStorage.removeItem('wx_openid');
        showAlert('拉取微信授权失败,请重新登录!');
    },
    _requestAuthSuccess: function (response) {
        LoginBtnUnit.prototype._requestAuthSuccess.call(this);
        var userInfo = JSON.parse(response);
        if (userInfo.result && userInfo.result != 0) {
            hideLoading();
            cc.sys.localStorage.removeItem('wx_openid');
            showAlert('微信授权验证失败!请重新登录!');
            return;
        }
        cc.sys.localStorage.setItem('wx_openid', userInfo.openid);
        cc.sys.localStorage.setItem('nickname', encodeURIComponent(userInfo.nickname));
        cc.sys.localStorage.setItem('sex', userInfo.sex);
        cc.sys.localStorage.setItem('province', userInfo.province);
        cc.sys.localStorage.setItem('city', userInfo.city);
        cc.sys.localStorage.setItem('country', userInfo.country);
        cc.sys.localStorage.setItem('headimgurl', userInfo.headimgurl);
        cc.sys.localStorage.setItem('unionid', userInfo.unionid);
        this.doLogin(userInfo, 'wx');
    }
});